package com.whut.utils;

import com.google.common.collect.Range;

/**
*一个用来转换数学范围的类
* @author fuzhenjie
* @date 19.8.6 19:32
*/
public class RangeHelper {

	/**
	 * 用"^"来表示无穷
	 */
	private final static String INFINITE = "^";
	
	public static void main(String[] args) {
		/*RangeHelper rangeTest = new RangeHelper();
		System.out.println(rangeTest.isRangeStringValid("[2.3,2]"));*/
		String range = RangeHelper.isRangeStringValid("[a,2]");
		/*System.out.println(range.lowerEndpoint());
		System.out.println(range.upperEndpoint());
		System.out.println(range.contains(-10000000.00f));
		System.out.println(range.contains(2.0f));
		System.out.println(range.contains(3.0f));*/
		System.out.println(range);
	}
	
	
	/**
	 * 检验一个字符串是否是区间范围
	 * @param rangeString 一个待检验的数学范围串
	 * @return 返回出错信息
	 */
	public static String isRangeStringValid(String rangeString){
		int length = rangeString.length();
		if(length<5) {
			return "格式错误";
		}
		byte[] byteArray = rangeString.getBytes();
		boolean isMarginRight = (byteArray[0]==91||byteArray[0]==40)&&(byteArray[length-1]==93||byteArray[length-1]==41);
		if(!isMarginRight) {
			return "边界符号错误";
		}
		byte[] targetArray = new byte[length-2];
		System.arraycopy(byteArray, 1, targetArray, 0, length-2);
		String toSplitStr = new String(targetArray);
		System.out.println(toSplitStr);
		String[] strArr = toSplitStr.split(",");
		if(strArr.length != 2) {
			return "内部元素错误";
		}
		if(!INFINITE.equals(strArr[0])) {
			try {
				Float.valueOf(strArr[0]);
			} catch (Exception e) {
				return "数据格式不正确";
			}	
		}
		if(!INFINITE.equals(strArr[1])) {
			try {
				Float.valueOf(strArr[1]);
			} catch (Exception e) {
				return "数据格式不正确";
			}	
		}

		if(!INFINITE.equals(strArr[0])&&!INFINITE.equals(strArr[1])){
			if(Float.valueOf(strArr[0])>Float.valueOf(strArr[1])){
				return "左端输入数字不能大于右端";
			}
		}
		
		return "correct";
	}
	
	
	/**
	 * 根据一个合法的输入串 返回一个range对象
	 * @param rangeString 一个合法的数学范围串
	 * @return Range<Float>
	 */
	public static Range<Float> getInstance(String rangeString) {
		
		int length = rangeString.length();
		byte[] byteArray = rangeString.getBytes();
		boolean isLeftOpen = byteArray[0] == 40;
		boolean isRightOpen = byteArray[0] == 41;
		byte[] targetArray = new byte[length-2];
		System.arraycopy(byteArray, 1, targetArray, 0, length-2);
		String toSplitStr = new String(targetArray);
		
		String[] strArr = toSplitStr.split(",");
		Float s = -Float.MAX_VALUE,e = Float.MAX_VALUE;
		if(!INFINITE.equals(strArr[0])){
			s = Float.valueOf(strArr[0]);
		}
		if(!INFINITE.equals(strArr[1])){
			e = Float.valueOf(strArr[1]);
		}

		Range<Float> range = null;
		if(isLeftOpen&&isRightOpen){
			range = Range.open(s,e);
		}else if(isLeftOpen && !isRightOpen){
			range = Range.openClosed(s,e);
		}else if(!isLeftOpen && isRightOpen){
			range = Range.closedOpen(s,e);
		}else if(!isLeftOpen&&!isRightOpen){
			range = Range.closed(s,e);
		}

		return range;
	}

	
}
